package com.tang.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * CreateTime: 2016-06-11上午9:53
 * Author: wjkjinke00@126.com
 * Description:
 */
public class GsonUtil {

    /**
     * 将json字符串解析成对象
     *
     * @param json
     * @param token
     * @return T  各种对象
     */
    public static <T> T parseJson(String json, TypeToken<T> token) {
        Gson g = new Gson();
        try {
            @SuppressWarnings("unchecked")
            T t = (T) g.fromJson(json, token.getType());
            return t;
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T parseJson(String json, Class<T> cls) {
        if (json == null) {
            return null;
        }
        Gson g = new Gson();
        try {
            T t = (T) g.fromJson(json, cls);
            return t;
        } catch (Exception e) {
            return null;
        }
    }


    public static <T> String toJsonStr(T t) {
        Gson g = new Gson();
        String s = g.toJson(t);
        return s;
    }

}
